<template>
  <div class="form-designer-container">
    <div class="toolbar">
      <h2>表单设计器</h2>
      <div class="actions">
        <el-input v-model="formName" placeholder="表单名称" style="width: 200px;"></el-input>
        <el-button type="primary" @click="saveForm">保存表单</el-button>
        <el-button @click="previewForm">预览表单</el-button>
        <el-button @click="exportJson">导出 JSON</el-button>
      </div>
    </div>

    <div class="designer-wrapper">
      <!-- 左侧组件库 -->
      <div class="component-library">
        <h4>表单组件</h4>
        <div class="component-list">
          <div 
            v-for="comp in componentList" 
            :key="comp.type"
            class="component-item"
            draggable="true"
            @dragstart="startDrag($event, comp)">
            <i :class="'el-icon-' + comp.icon"></i>
            <span>{{ comp.label }}</span>
          </div>
        </div>
      </div>

      <!-- 中间设计区 -->
      <div class="canvas-area"
        @dragover.prevent="onCanvasDragOver"
        @dragleave="onCanvasDragleave"
        @drop="onCanvasDrop"
        :class="{ 'drag-over': isDragOver }">
        <div class="form-fields">
          <div v-if="formFields.length === 0" class="empty-tip">
            下拆组件到这里来设计表单
          </div>
          <div v-for="(field, index) in formFields" :key="field.id" class="form-field">
            <div class="field-header">
              <span class="field-label">{{ field.label }}</span>
              <div class="field-actions">
                <el-button 
                  type="text" 
                  size="small" 
                  @click="selectField(index)">编辑</el-button>
                <el-button 
                  type="text" 
                  size="small" 
                  @click="removeField(index)" 
                  style="color: #f56c6c;">删除</el-button>
              </div>
            </div>
            <div class="field-preview">
              <component-preview :field="field"></component-preview>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="property-panel">
        <h4>属性设置</h4>
        <div v-if="selectedFieldIndex !== null" class="property-form">
          <el-form size="small" label-width="80px">
            <el-form-item label="字段名">
              <el-input v-model="formFields[selectedFieldIndex].name"></el-input>
            </el-form-item>
            <el-form-item label="标签">
              <el-input v-model="formFields[selectedFieldIndex].label"></el-input>
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="formFields[selectedFieldIndex].type" disabled>
                <el-option label="文本" value="text"></el-option>
                <el-option label="整数" value="number"></el-option>
                <el-option label="日期" value="date"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否必填">
              <el-switch v-model="formFields[selectedFieldIndex].required"></el-switch>
            </el-form-item>
            <el-form-item label="提示信息">
              <el-input v-model="formFields[selectedFieldIndex].placeholder" type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div v-else class="empty-tip">
          选择表单中的字段来设置属性
        </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog title="表单预览" :visible.sync="previewVisible" width="600px">
      <div class="form-preview">
        <el-form ref="previewForm" label-width="100px">
          <el-form-item 
            v-for="field in formFields" 
            :key="field.id"
            :label="field.label"
            :required="field.required">
            <el-input 
              v-if="field.type === 'text'"
              v-model="previewData[field.name]"
              :placeholder="field.placeholder"></el-input>
            <el-input 
              v-else-if="field.type === 'number'"
              v-model.number="previewData[field.name]"
              type="number"
              :placeholder="field.placeholder"></el-input>
            <el-date-picker 
              v-else-if="field.type === 'date'"
              v-model="previewData[field.name]"
              type="date"
              :placeholder="field.placeholder"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
const ComponentPreview = {
  props: ['field'],
  template: `
    <div>
      <el-input 
        v-if="field.type === 'text'"
        :value="field.label"
        :placeholder="field.placeholder"
        disabled></el-input>
      <el-input 
        v-else-if="field.type === 'number'"
        type="number"
        :placeholder="field.placeholder"
        disabled></el-input>
      <el-date-picker 
        v-else-if="field.type === 'date'"
        type="date"
        :placeholder="field.placeholder"
        disabled></el-date-picker>
    </div>
  `
}

export default {
  name: 'FormDesigner',
  components: {
    ComponentPreview
  },
  data() {
    return {
      formName: '',
      previewVisible: false,
      isDragOver: false,
      selectedFieldIndex: null,
      formFields: [],
      previewData: {},
      componentList: [
        { type: 'text', label: '文本框', icon: 'edit' },
        { type: 'number', label: '整数', icon: 'sort-numeric' },
        { type: 'date', label: '日期', icon: 'date' }
      ],
      nextFieldId: 1
    }
  },
  methods: {
    startDrag(event, component) {
      event.dataTransfer.effectAllowed = 'copy'
      event.dataTransfer.dropEffect = 'copy'
      event.dataTransfer.setData('componentType', component.type)
      event.dataTransfer.setData('componentLabel', component.label)
    },

    onCanvasDragOver(event) {
      event.preventDefault()
      this.isDragOver = true
    },

    onCanvasDragleave(event) {
      if (event.target.classList.contains('canvas-area')) {
        this.isDragOver = false
      }
    },

    onCanvasDrop(event) {
      event.preventDefault()
      event.stopPropagation()
      this.isDragOver = false

      const componentType = event.dataTransfer.getData('componentType')
      const componentLabel = event.dataTransfer.getData('componentLabel')

      if (componentType) {
        const newField = {
          id: `field-${++this.nextFieldId}`,
          name: `field_${this.nextFieldId}`,
          label: componentLabel,
          type: componentType,
          required: false,
          placeholder: `请输入${componentLabel}`
        }
        this.formFields.push(newField)
      }
    },

    selectField(index) {
      this.selectedFieldIndex = index
    },

    removeField(index) {
      this.$confirm('是否删除该字段?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formFields.splice(index, 1)
        if (this.selectedFieldIndex === index) {
          this.selectedFieldIndex = null
        }
        this.$message.success('删除成功')
      }).catch(() => {})
    },

    previewForm() {
      if (this.formFields.length === 0) {
        this.$message.error('表单为空，请先设计表单')
        return
      }
      this.previewData = {}
      this.previewVisible = true
    },

    submitForm() {
      const formDataStr = JSON.stringify(this.previewData, null, 2)
      console.log('提交的表单数据:', this.previewData)
      this.$message.success('表单提交成功')
      this.previewVisible = false
    },

    saveForm() {
      if (!this.formName.trim()) {
        this.$message.error('请输入表单名称')
        return
      }

      if (this.formFields.length === 0) {
        this.$message.error('表单为空，请先设计表单')
        return
      }

      const formData = {
        name: this.formName,
        content: JSON.stringify(this.formFields),
        description: '表单设计器穿设计的表单'
      }

      console.log('保存的表单:', formData)
      this.$message.success('表单保存成功')
    },

    exportJson() {
      if (this.formFields.length === 0) {
        this.$message.error('表单为空')
        return
      }

      const jsonStr = JSON.stringify(this.formFields, null, 2)
      const element = document.createElement('a')
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(jsonStr))
      element.setAttribute('download', `${this.formName || '表单'}.json`)
      element.style.display = 'none'
      document.body.appendChild(element)
      element.click()
      document.body.removeChild(element)
      
      this.$message.success('JSON 导出成功')
    }
  }
}
</script>

<style scoped>
.form-designer-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.toolbar {
  background: white;
  padding: 15px 20px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.actions {
  display: flex;
  gap: 10px;
}

.designer-wrapper {
  flex: 1;
  display: flex;
  gap: 10px;
  padding: 10px;
  overflow: hidden;
}

.component-library {
  width: 150px;
  background: white;
  border-radius: 4px;
  padding: 10px;
  overflow-y: auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.component-library h4 {
  margin: 0 0 10px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.component-list {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.component-item {
  padding: 8px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 3px;
  cursor: move;
  font-size: 12px;
  text-align: center;
  user-select: none;
  transition: all 0.2s;
}

.component-item:hover {
  background: #e6f7ff;
  transform: scale(1.02);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.canvas-area {
  flex: 1;
  background: white;
  border-radius: 4px;
  border: 2px dashed #ddd;
  padding: 10px;
  overflow: auto;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.canvas-area.drag-over {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.form-fields {
  min-height: 100%;
}

.empty-tip {
  color: #909399;
  text-align: center;
  padding: 40px 20px;
  font-size: 14px;
}

.form-field {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  transition: all 0.3s;
}

.form-field:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.field-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.field-label {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
}

.field-actions {
  display: flex;
  gap: 5px;
}

.field-preview {
  padding: 8px;
  background: #f5f7fa;
  border-radius: 3px;
}

.property-panel {
  width: 220px;
  background: white;
  border-radius: 4px;
  padding: 10px;
  overflow-y: auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.property-panel h4 {
  margin: 0 0 10px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.property-form {
  font-size: 12px;
}
</style>